package util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DBUtil {
    // 数据库连接信息
    private static final String URL = "jdbc:mysql://localhost:3306/user?useSSL=false&serverTimezone=UTC&characterEncoding=UTF-8&allowPublicKeyRetrieval=true";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "331307";
    
    // 静态代码块加载驱动
    static {
        try {
            // 注册驱动的两种方式都试一下
            DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver());
            Class.forName("com.mysql.cj.jdbc.Driver");
            System.out.println("数据库驱动加载成功");
        } catch (ClassNotFoundException | SQLException e) {
            System.out.println("数据库驱动加载失败：" + e.getMessage());
            e.printStackTrace();
        }
    }
    
    // 获取数据库连接
    public static Connection getConnection() {
        Connection conn = null;
        try {
            System.out.println("正在尝试连接数据库...");
            conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
            System.out.println("数据库连接成功！");
            return conn;
        } catch (SQLException e) {
            System.out.println("数据库连接失败！错误信息：");
            System.out.println("Error Code: " + e.getErrorCode());
            System.out.println("SQL State: " + e.getSQLState());
            System.out.println("Message: " + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }
    
    // 测试连接方法
    public static void testConnection() {
        Connection conn = null;
        try {
            conn = getConnection();
            if (conn != null) {
                System.out.println("数据库连接测试成功！");
            } else {
                System.out.println("数据库连接测试失败！");
            }
        } finally {
            closeConnection(conn);
        }
    }
    
    // 关闭数据库连接
    public static void closeConnection(Connection conn) {
        if (conn != null) {
            try {
                conn.close();
                System.out.println("数据库连接已关闭");
            } catch (SQLException e) {
                System.out.println("关闭数据库连接失败：" + e.getMessage());
                e.printStackTrace();
            }
        }
    }
    
    // 主方法用于测试
    public static void main(String[] args) {
        testConnection();
    }
} 